package com.winit.tree.web;

import com.winit.common.base.bean.ExecuteResult;
import com.winit.common.base.web.BaseController;
import com.winit.tree.manager.TreeManager;
import com.winit.tree.model.TreeNode;
import com.winit.tree.model.TreeType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Api(value = "productLine", tags = {"productLine"}, description = "productLine")
@RestController
@RequestMapping("/api/v1/productLine")
public class ProductLineController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(ProductLineController.class);

    @Autowired
    private TreeManager treeManager;

    @RequestMapping(value = "/getProductLineTree", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取ProductLine tree")
    @ResponseBody
    public Map getProductLineTree(@ApiParam(value = "productLineId, 根id，缺省默认查整棵树")@RequestParam(value = "productLineId", required = false)String productLineId){
        TreeNode productLine = this.treeManager.getTree(productLineId, TreeType.PRODUCT_LINE);
        return this.getRtn(BaseController.REQUEST_SUCCESS, BaseController.REQUEST_SUCCESS_MSG, productLine);
    }


    @RequestMapping(value = "/saveProductLine", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "创建/更新ProductLine")
    @ResponseBody
    public Map saveProductLine(@RequestBody TreeNode treeNode){
        ExecuteResult<TreeNode> rs = null;
        if (StringUtils.isEmpty(treeNode.getId())){
            log.info("未找到ProductLine id,将执行创建");
            if (StringUtils.isEmpty(treeNode.getType())){
                treeNode.setType(TreeType.PRODUCT_LINE);
            }
            rs = this.treeManager.createTreeNode(treeNode);
        }else {
            log.info("productLine id存在，将执行更新");
            rs = this.treeManager.updateTreeNode(treeNode);
        }

        Object data = rs.getData() == null ? null : rs.getData().getId();
        return this.getRtn(rs.getCode(), rs.getDesc(), data);
    }



    @RequestMapping(value = "/deleteProductLine", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "删除ProductLine")
    @ResponseBody
    public Map deleteProductLine(@ApiParam(value = "productLineId")@RequestParam(value = "productLineId", required = true)String productLineId){
        ExecuteResult executeResult= this.treeManager.deleteTreeNodeById(productLineId);
        return this.getRtn(executeResult.getCode(), executeResult.getDesc());
    }


}
